<script lang="ts" setup>
import idcardMakBack from '@/assets/query/idcard-mask-back.png'
import idcardMakFace from '@/assets/query/idcard-mask-face.png'
import makFace from '@/assets/query/mask-face.png'

import { onMounted, ref, onUnmounted, reactive, computed } from 'vue';
import { useUserStore } from '@/stores/index';
import { Icon } from 'vant';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const videoEl = ref<HTMLVideoElement | null>(null)
const canvasEl = ref<HTMLCanvasElement | null>(null)

const maskUrl = computed(() => {
  if (route.query.type == '1') {
    return idcardMakFace
  } else if (route.query.type == '2') {
    return idcardMakBack
  } else if (route.query.type == '3') {
    return makFace
  }
})
const videoStyle = reactive({
  transform: 'rotateY(0deg)'
})
const isIphone = navigator.userAgent.includes('iPhone')
const contentHeight = document.documentElement.clientHeight
let stream
let facingMode: 'environment' | 'user' = 'user'
const realitySize = {//实际使用的分辨率
  width: 0,
  height: 0
}
async function showCamera() {
  if (facingMode == 'user') {
    videoStyle.transform = 'rotateY(180deg)'
  } else {
    videoStyle.transform = 'rotateY(0deg)'
  }
  let aspectRatio = 4 / 3
  if (navigator.userAgent.includes('Android') || navigator.userAgent.includes('iPhone')) {
    aspectRatio = 16 / 9
  }
  stream = await navigator.mediaDevices.getUserMedia({
    audio: false,
    video: {
      facingMode,
      width: {
        ideal: facingMode == 'user' ? 1280 : 2560,
        // min: 1280, // 最小宽度
        // max: 2560, // 最大宽度，可以根据需要设置为更高的值，比如3840（4K）
      },
      height: {
        ideal: facingMode == 'user' ? 720 : 1440,
        // min: 720, // 最小高度
        // max: 1440 // 最大高度，可以根据需要设置为更高的值，比如2160（4K）
      },
      aspectRatio
    }
  })
  const videoTrack = stream.getVideoTracks()[0];
  const settings = videoTrack.getSettings();
  realitySize.height = settings.height
  realitySize.width = settings.width
  console.log(`实际分辨率: ${settings.width}x${settings.height}`);

  const video = videoEl.value!
  // 旧的浏览器可能没有 srcObject
  if ("srcObject" in video) {
    video.srcObject = stream;
  } else {
    // 防止在新的浏览器里使用它，应为它已经不再支持了
    //@ts-ignore
    video.src = window.URL.createObjectURL(stream);
  }
  video.onloadedmetadata = function (e) {
    video.play();
  };
  if(isIphone){
    setTimeout(() => video.play(), 100)
  }
}
onMounted(() => {
  showCamera()
})
function reserve() {
  close()
  facingMode = facingMode == 'environment' ? 'user' : 'environment'
  showCamera()
}
function close() {
  stream.getTracks().forEach(track => {
    track.stop();
  });
}

//拍照
function canvasToBaseUrl() {
  const canvas = canvasEl.value!
  const video = videoEl.value!
  const ctx = canvas.getContext('2d')!;
  if(isIphone){
    canvas.width = realitySize.height;
    canvas.height =realitySize.width;
  }else{
    canvas.width = realitySize.width;
    canvas.height = realitySize.height;
  }
 
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  const dataURL = canvas.toDataURL('image/jpeg', 0.6);
  console.log('压缩后的大小:'+getBase64ImageSize(dataURL)+'kb')
  return dataURL
}
let isCapture = ref(false)
const captureUri = ref('')
function onCapture() {
  captureUri.value =  canvasToBaseUrl()
  isCapture.value = true;
}
function getBase64ImageSize(base64) {
    let str = atob(base64.split(',')[1]);
    let bytes = str.length;
    return bytes / 1024;
}
//确认选择照片
function confirm() {
  if (route.query.type == '1') {
    userStore.idcardFaceUri =  captureUri.value
  } else if (route.query.type == '2') {
    userStore.idcardBackUri =  captureUri.value
  } else if (route.query.type == '3') {
    userStore.faceUri =  captureUri.value
  }
  const path = `${route.query.path}`
  router.replace(path)
}
onUnmounted(() => {
  console.log('onUnmounted')
  close()
})
defineExpose({
  showCamera
})
</script>
<template>
  <div class="video-box" :style="{ height: contentHeight + 'px' }">
    <video ref="videoEl" :style="videoStyle"  playsinline muted ></video>
    <div class="mask-box">
      <img class="mask-img"  :src="maskUrl" />
      <div class="options">
        <div style="width: 30px;"></div>
        <img @click="onCapture" src="@/assets/query/capture.png" class="capture"></img>
        <div @click="reserve" class="reserve">
          <img src="@/assets/query/reserve.png" alt="">
          <span>翻转</span>
        </div>
      </div>
    </div>
    <Transition>
      <div v-if="isCapture" class="preview">
        <div class="p-head">
          <Icon @click="isCapture = false" name="cross" size="30" color="#fff" />
          <Icon @click="confirm" name="success" size="30" color="#fff" />
        </div>
        <img class="preview-img" :src="captureUri" alt="">
      </div>
    </Transition>

    <canvas ref="canvasEl" style="display: none;"></canvas>
  </div>
</template>
<style lang="less" scoped>
.video-box {
  position: relative;

  video {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: fill;

    background-color: black;
  }

  .mask-box {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    // background-image: url(@/assets/query/idcard-mask.png);
    background-size: 100% 100%;
    .mask-img{
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .options {
      position: absolute;
      width: 80%;
      display: flex;
      justify-content: space-around;
      bottom: 10%;
      background: #FFFFFF10;
      border-radius: 32px 32px 32px 32px;
      // opacity: 0.1;
      padding: 10px 0;
      color: #fff;
      transform: translateX(-50%);
      left: 50%;

      .capture {
        width: 50px;
        height: 50px;
      }

      .reserve {
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: 12px;
        align-items: center;


        img {
          width: 30px;
          height: 30px;
        }
      }
    }
  }

  .preview {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 11;
    left: 0;
    top: 0;

    .p-head {
      position: absolute;
      display: flex;
      justify-content: space-between;
      padding: 25px 30px;
      width: 100%;
    }

    img {
      width: 100%;
      height: 100%;

    }
  }

  .v-enter-active,
  .v-leave-active {
    transition: opacity 0.3s ease;
  }

  .v-enter-from,
  .v-leave-to {
    opacity: 0;
  }
}
</style>
